/* -+- file  ./kf2/GUI/AccountSelector.cs -+- */
/*
 * kf2 jabber client
 * ~~~~~~~~~~~~~~~~~
 *
 * Copyright (C) 2006-2007 Przemysław Sitek
 * 				<przemyslaw.sitek at wp.pl> 
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

using System;
using Habazie.kf2.Core;
using Habazie.kf2.Net;

namespace Habazie.kf2.GUI
{
	
	public class AccountSelector : Gtk.ComboBox
	{
		private Gtk.ListStore		m_Store;
		private ConnectionManager	m_Connections = null;
		
		public AccountSelector() : base ()
		{
			m_Store = new Gtk.ListStore (typeof (Account), typeof (string));
			Model = m_Store;
			Gtk.CellRendererText text = new Gtk.CellRendererText ();
			PackStart (text, true);
			AddAttribute (text, "markup", 1);
		}
		
		public ConnectionManager Connections {
			get { return m_Connections; }
			set {
				if (m_Connections != null)
					m_Connections.Changed -= OnAccountsChanged;
				m_Connections = value;
				m_Connections.Changed += OnAccountsChanged;
				Update ();
			}
		}
		
		public Habazie.kf2.Net.Account Account {
			get {
				Gtk.TreeIter iter;
				
				if (GetActiveIter (out iter))
					return (Account) m_Store.GetValue (iter, 0);
				else
					return null;
			}
			set {
				Gtk.TreeIter iter;
				if (m_Store.GetIterFirst (out iter)) {
					do {
						if ((Account)m_Store.GetValue (iter, 0) == (Account) value) {
							SetActiveIter (iter);
						}
					} while (m_Store.IterNext (ref iter));
				}
			}
		}
		
		private void Update ()
		{
			m_Store.Clear ();
			if (m_Connections != null) {
				foreach (Account acc in m_Connections) {
					m_Store.AppendValues (acc, String.Format ("{0} <small><i>{1}@{2}</i></small>",
																acc.Name, acc.User, acc.Server));
				}
			}
		}
		
		protected virtual void OnAccountsChanged (object sender, EventArgs args)
		{
			Update ();
		}
	}
	
}
